package io.github.betwowt;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * optional
 */
public class OptionalDemo {


    /**
     * Optional ifPresent demo
     */
    @Test
    public void ifPresent() {
        Person person = null;
        // ofNullable 与 of 当 T 为null时 Optional.of() 会抛出空指针
        Optional<Person> optionalPerson = Optional.ofNullable(person);
//        Optional<Person> optionalPerson1 = Optional.of(person);
        // ifPresent 的匿名函数会在persion 对象不为null时执行
        optionalPerson.ifPresent(System.out::println);

        // ifPresentOrElse person对象是空时 执行匿名函数
        optionalPerson.ifPresentOrElse(System.out::println, () -> {
            System.out.println("persion is null;");
        });
    }


    /**
     * Optional map demo
     */
    @Test
    public void map() {
        Person person = new Person("bob",1,null);
        Optional<Person> optionalPerson = Optional.ofNullable(person);
        // map 方法会先执行 ifPresent 判断表达式是否是null
        optionalPerson.map(p -> p.getPhone()).stream().forEach(e-> System.out.println(e));
        System.out.println("add phone -> 110 , 112 ");
        person.setPhone(Arrays.asList("110","112"));
        optionalPerson.map(p -> p.getPhone()).stream().forEach(e-> System.out.println(e));
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class Person {
        private String name;
        private Integer id;
        private List<String> phone;
    }
}
